<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" stripe border>
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <!-- 权限图 -->
            <el-row
              :class="['elBottom', index === 0 ? 'elTop' : '', 'vcenter']"
              v-for=" (item, index) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag
                  class="elTag"
                  type="primary"
                  closable
                  @close="removeTag(scope.row, item.id)"
                >
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[index2 === 0 ? '' : 'elTop', 'vcenter']"
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      class="elTag"
                      type="success"
                      closable
                      @close="removeTag(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      class="elTag"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeTag(scope.row, item3.id)"
                    >
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" align="center"></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRolesById(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="getRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹出框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightsDialogVisible"
      @close="setRightsDialogClose"
      class="dialog"
    >
      <!-- 树形结构 -->
      <el-tree
        :data="rightList"
        :props="rightProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultArr"
        ref="treeRights"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <Dialog
      :dialogVisible = "visible"
      :diaSonType="diaparentType"
      :addRoles="addRoles"
      @changeVisible="changeVisible"
      @sonRoles="parentRoles"
      @editSonRoles="parentEditRoles"
    />
  </div>
</template>

<script>
import Dialog from '@/components/common/Dialog'
export default {
  data () {
    return {
      // Dialog 组件的显示
      visible: false,
      diaparentType: '',
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      roleList: [],
      // 弹出框显示
      setRightsDialogVisible: false,
      // 权限列表
      rightList: [],
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 已存在树形节点组成的数组
      defaultArr: [],
      // 点击分配权限时的当前用户的 id
      roleId: '',
      // 点击编辑时当前用户的 id
      editRoleId: ''
    }
  },
  components: {
    Dialog
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 根据 Id 删除权限
    async removeTag (role, rightId) {
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('已取消这次删除')
      // console.log('已经删除了')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      //  返回的数据就是删除后的数据
      role.children = res.data
    },
    // 打开权限管理，获取树形权限列表以及打开dialog
    async getRightsDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败！')
      this.rightList = res.data
      // 执行递归函数 找寻到该用户已有的权限
      this.getLeafKeys(role, this.defaultArr)
      this.setRightsDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id
    // 并保存到 defaultArr 中
    getLeafKeys (node, arr) {
      // 不包含就是children就是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 遍历一级节点和二级节点
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭模态框 清除 defaultArr 的数据
    setRightsDialogClose () {
      this.defaultArr = []
    },
    // 点击确定按钮，发送请求设置权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRights.getCheckedKeys(),
        ...this.$refs.treeRights.getHalfCheckedKeys()
      ]
      const rids = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')
      this.setRightsDialogVisible = false
      this.getRolesList()
      this.$message.success('分配权限成功')
    },
    // 点击添加角色
    addDialog () {
      this.diaparentType = 'addroles'
      this.visible = true
    },
    //  改变添加角色模态框状态
    changeVisible () {
      this.visible = false
    },
    // 点击模态框确定后执行的代码
    async parentRoles (data) {
      console.log(data)
      const { data: res } = await this.$http.post('roles', { ...data })
      if (res.meta.status !== 201) return this.$message.error('添加角色失败！')
      this.$message.success('添加角色成功！')
      // 添加到 roleList中 实现页面更新 或 重新获取角色列表
      // this.roleList.push(res.data)
      this.getRolesList()
      this.visible = false
    },
    // 删除 角色 通过 id
    async removeRolesById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err) // 捕获错误，并且renturn出去
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败！')
      this.$message.success('删除成功')
      // 重新获取角色列表
      this.getRolesList()
    },
    // 通过 id 编辑角色
    editRolesById (role) {
      this.diaparentType = 'editroles'
      this.addRoles = { ...role }
      this.editRoleId = role.id
      this.visible = true
    },
    // 接受子组件传来的方法 进行修改
    async parentEditRoles (data) {
      const { data: res } = await this.$http.put(`roles/${this.editRoleId}`, { ...data })
      if (res.meta.status !== 200) return this.$message.error('修改角色失败！')
      // 关闭模态框
      this.visible = false
      this.$message.success('修改角色成功！')
      // 重新获取 角色列表
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.vcenter {
  display: flex;
  align-items: center;
}
.dialog {
  ::v-deep .el-dialog__body {
    height: 500px;
    overflow: hidden;
    overflow-y: auto;
    border-bottom: 1px solid #eee;
    border-top: 1px solid #eee;
  }
}
</style>
